package com.leisai.manager.service.impl;

import com.leisai.manager.common.utils.DateUtils;
import com.leisai.manager.common.utils.StringUtil;
import com.leisai.manager.dao.IndustryMapper;
import com.leisai.manager.dao.ReportMapper;
import com.leisai.manager.dao.SalesDataMapper;
import com.leisai.manager.dao.WriteMapper;
import com.leisai.manager.dto.IndustryDTO;
import com.leisai.manager.dto.ReportDTO;
import com.leisai.manager.dto.WriteDTO;
import com.leisai.manager.pojo.*;
import com.leisai.manager.service.WriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jim
 * @Date: 2021/12/02/15:55
 * @Description:
 */
@Service
public class WriteServiceImpl implements WriteService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    WriteMapper writeMapper ;
    @Autowired
    ReportMapper reportMapper;
    @Autowired
    IndustryMapper industryMapper;
    @Autowired
    SalesDataMapper salesDataMapper;
    @Override
    public Map<String, Object> addWrite(List<Write> writes) {
        Map<String,Object> data = new HashMap();
        try {
            int result = writeMapper.insert(writes);
            if(result == 0){
                data.put("code",0);
                data.put("msg","新增失败！");
                logger.error("报表[新增]，结果=新增失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","新增成功！");
            logger.info("报表[新增]，结果=新增成功！");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("报表[新增]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> updateWrite(List<Write> writes) {
        Map<String,Object> data = new HashMap();
        try {

             writeMapper.deleteByPrimaryKey(writes.get(0).getReportId());
            int result = writeMapper.insert(writes);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败！");
                logger.error("报表[更新]，结果=更新失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","更新成功！");
            logger.info("报表[更新]，结果=更新成功！");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("报表[更新]异常！", e);
            return data;
        }
        return data;
    }
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    @Override
    public List<WriteDTO> getWrite(Integer reportId) {
        List<WriteDTO> writes = writeMapper.selectByPrimaryKey(reportId);
        if (writes == null){
            logger.error("查看历史报表错误！");
        }
        return writes;
    }

    @Override
    public Map<String, Object> calculateTotal(Integer reportId) {
        Map<String ,Object> data = new HashMap<>();
        Report report = reportMapper.selectByPrimaryKey(reportId);
        Industry industry = null ;
        if (report != null){
             industry = industryMapper.selectByPrimaryKey(report.getIndustryId());
        }
        ReportDTO reportDTO = new ReportDTO();
        reportDTO.setYear(report.getYear());
        reportDTO.setIndustryId(industry.getIndustryId());
        reportDTO.setIndustryName(industry.getIndustryName());
        try {
            //初始化行业销售数据
             salesDataMapper.initSaleData(report.getYear());
             //将当前细分行业的销售数据更新
            SalesData salesData = setSalesDate(reportDTO);
            //
            List<IndustryDTO> industryList = industryMapper.getIndustryList(new IndustryDTO());

            String pids = industry.getPids();
            String[] pidArray = pids.split(",");
            //细分行业都有三层父级
            for (int i = pidArray.length -1 ; i >=0  ; i-- ){
                Integer industryId = Integer.parseInt( StringUtil.getBrace(pidArray[i]));
                List<Integer> industryIds = new ArrayList<>();
                for (IndustryDTO industryDTO: industryList) {
                    Integer pid =   industryDTO.getPid().intValue();
                    if (pid.equals(industryId) ){
                        industryIds .add(industryDTO.getIndustryId());
                    }
                }

                Integer result = setParentSalesDate(industryIds,report.getYear(),industryId);
                if(result == 0){
                    data.put("code",0);
                    data.put("msg","合计失败！");
                    logger.error("报表合计计算失败！");
                    return data;
                }
                data.put("code",1);
                data.put("msg","合计计算成功！");
                logger.info("报表合计计算成功！");
            }
        }catch (Exception e){
            data.put("code",0);
            data.put("msg","合计失败！");
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public SalesData setSalesDate(ReportDTO reportDTO) {
        SalesData salesData = new SalesData();
        List<Integer> industryList = new ArrayList<>();
        industryList.add(reportDTO.getIndustryId());
        //市场需求
        List<TreeNode> industryTotal = writeMapper.getIndustryTotal(industryList, reportDTO.getYear(), "c%");
        Double marketRequirement =industryTotal.get(0).getValue();
        salesData.setMARKET_REQUIREMENT(marketRequirement);
        //销售额
        industryTotal = writeMapper.getIndustryTotal(industryList, reportDTO.getYear(), "d%");
        Double saleResults = industryTotal.get(0).getValue();
        salesData.setSALE_RESULTS(saleResults);
        //市场占有率
        Double marketShare = 0d;
        if (!marketRequirement.equals(0)){
            marketShare = saleResults / marketRequirement;
        }
        salesData.setMARKET_SHARE(marketShare * 100);
        //销售目标
        industryTotal = writeMapper.getIndustryTotal(industryList, reportDTO.getYear(), "f%");
        Double saleTarget = industryTotal.get(0).getValue();
        salesData.setSALE_TARGET(saleTarget);
        //目标完成率
        Double saleCompletion = 0d;
        if (!saleTarget.equals(0)){
            saleCompletion = saleResults / saleTarget ;
        }
        salesData.setSALE_COMPLETION(saleCompletion * 100);
        //去年的销售额
        industryTotal = writeMapper.getIndustryTotal(industryList, reportDTO.getYear(), "h%");
        Double lastYearSales = industryTotal.get(0).getValue();
        salesData.setLAST_YEAR_SAlES(lastYearSales);
        //同比增长率
        Double growthRate = 0d;
        if (!lastYearSales.equals(0)){
            growthRate = (saleResults - lastYearSales)/lastYearSales;
        }
        salesData.setGROWTH_RATE(growthRate*100);

        salesData.setYEAR(reportDTO.getYear());
        salesData.setINDUSTRY_ID(reportDTO.getIndustryId());
        salesData.setINDUSTRY_NAME(reportDTO.getIndustryName());
        salesData.setUPDATE_TIME(DateUtils.getCurrentDateToDate());


        int result = salesDataMapper.updateByPrimaryKeySelective(salesData);
        if (result <= 0){
            logger.error(reportDTO.getIndustryName()+"的合计更新失败！");
        }

        return salesData;
    }

    @Override
    public Integer setParentSalesDate(List<Integer> industryIds ,String year,Integer pid) {
        int result = 1 ;
        SalesData combinedDate = salesDataMapper.getCombinedDate(industryIds,year);

        combinedDate.setUPDATE_TIME(DateUtils.getCurrentDateToDate());
        combinedDate.setINDUSTRY_ID(pid);
        combinedDate.setYEAR(year);
        combinedDate.setINDUSTRY_NAME( industryMapper.selectByPrimaryKey(pid).getIndustryName() );

        //计算百分比
        Double market_requirement = combinedDate.getMARKET_REQUIREMENT();
        Double sale_results = combinedDate.getSALE_RESULTS();
        Double sale_target = combinedDate.getSALE_TARGET();
        Double last_year_sAlES = combinedDate.getLAST_YEAR_SAlES();
        try {

            Double market_share = (sale_results/market_requirement )*100;
            Double sale_completion = (sale_results / sale_target)*100;
            Double growth_rate = ((sale_results - last_year_sAlES)/last_year_sAlES)*100;
            combinedDate.setMARKET_SHARE(market_share);
            combinedDate.setSALE_COMPLETION(sale_completion);
            combinedDate.setGROWTH_RATE(growth_rate);

             result =  salesDataMapper.updateByPrimaryKeySelective(combinedDate);
        }catch (Exception e){
            logger.error("合计计算失败");
            result = 0 ;
            e.printStackTrace();
        }
        return result;
    }

}
